<template>
  <div class="box" ref="targetElement">
    <div class="search-box" ref="searchBox">
      <div class="search-top-box">
        <div class="search-top-left-box">
          <el-form label-width="110px" ref="div" :inline="true" :model="formSearch" @submit.native.prevent
            class="demo-form-inline">
            <el-form-item label="账户名称">
              <el-input @change="onSearch(1)" clearable class="form-width" v-model="formSearch.account_name"
                placeholder="输入账户名称"></el-input>
            </el-form-item>
            <el-form-item label="账户类型">
              <el-select filterable @change="onSearch(1)" clearable v-model="formSearch.type" placeholder="选择账户类型"
                class="form-width">
                <template v-if="activeName == 1">
                  <el-option label="公户" :value="1"></el-option>
                  <el-option label="私户" :value="2"></el-option>
                </template>
                <template v-if="activeName == 2">
                  <el-option label="客户" :value="1"></el-option>
                  <el-option label="经理" :value="2"></el-option>
                </template>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <div class="search-top-right-box">
          <!-- <p @click="moreSearchFunc">
            {{ moreSearchShow ? "收起" : "展开"
            }}<i :class="moreSearchShow ? 'el-icon-arrow-up' : 'el-icon-arrow-down'
              "></i>
          </p> -->
          <el-button type="primary" @click="onSearch(1)">查询</el-button>
          <el-button v-if="activeName == 1 && $isPer(permission, ['company_addCompany'])" type="primary"
            @click="addCompanyFunc(1)">新增主体账户</el-button>
          <el-button v-if="activeName == 2 && $isPer(permission, ['finance_addCurrent'])" type="primary"
            @click="addCompanyFunc(2)">新增往来账户</el-button>
        </div>
      </div>
    </div>
    <!-- table -->
    <div class="page-list" ref="pageList" v-loading="pageLoading">
      <div class="list-top-box">
        <div class="tab-box">
          <el-tabs v-model="activeName" @tab-click="tabClickFunc">
            <el-tab-pane label="主体账户" name="1"></el-tab-pane>
            <el-tab-pane label="往来账户" name="2"></el-tab-pane>
          </el-tabs>
        </div>
        <div class="list-top-box-right">
          <p class="list-top-box-left">
            已选<span class="num">{{ multipleSelection.length }}</span>/{{ tableData.length }}数据
          </p>
          <!-- 主体 -->
          <template v-if="activeName == 1">
            <el-button @click="editFunc" type="primary" :disabled="multipleSelection.length != 1"
              v-if="$isPer(permission, ['company_updCompany'])">编辑</el-button>
            <el-button @click="delFunc" type="danger" plain :disabled="multipleSelection.length == 0"
              v-if="$isPer(permission, ['company_delCompany'])">删除</el-button>
          </template>
          <!-- 往来 -->
          <template v-if="activeName == 2">
            <el-button @click="editFunc" type="primary" :disabled="multipleSelection.length != 1"
              v-if="$isPer(permission, ['finance_updateCurrent'])">编辑</el-button>
            <el-button @click="delFunc" type="danger" plain :disabled="multipleSelection.length == 0"
              v-if="$isPer(permission, ['purchase_deleteCurrent'])">删除</el-button>
          </template>
        </div>
      </div>
      <div class="table-box">
        <el-table border ref="table" @row-click="handleHighlightChangeTable" highlight-selection-row :header-cell-style="{
          background: '#FAFBFC',
          color: '#828A9D',
          textAlign: 'center',
        }" :cell-style="{ textAlign: 'center', color: '#1B2431' }" @selection-change="handleSelectionChange"
          :data="tableData" v-loading="tableLoading" height="100%">
          <el-table-column type="selection" width="80"></el-table-column>
          <el-table-column min-width="140px" prop="" label="ID">
            <template slot-scope="scope">
              <span v-if="activeName == 1">{{ $assemblyListNo('ZTZH', scope.row.id) }}</span>
              <span v-if="activeName == 2">{{ $assemblyListNo('WLZH', scope.row.id) }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('zh_zhmc')" min-width="180px" prop="account_name" label="账户名称"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column min-width="90px" prop="type" label="账户类型" show-overflow-tooltip
            v-if="activeName == 1 && $fieldShowFunc('zh_zhlx')">
            <template slot-scope="scope">
              {{ scope.row.type == 1 ? '公户' : '私户' }}
            </template>
          </el-table-column>
          <el-table-column min-width="90px" prop="type" label="账户类型" show-overflow-tooltip
            v-if="activeName == 2 && $fieldShowFunc('zh_zhlx')">
            <template slot-scope="scope">
              {{ scope.row.type == 1 ? '客户' : '经理' }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('zh_zh')" min-width="180px" prop="account_number" label="账号"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('zh_khh')" min-width="180px" prop="opening_bank" label="开户行"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('zh_sh')" min-width="180px" prop="Tax_ID" label="税号"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.Tax_ID || '--' }}
            </template>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('zh_dz')" min-width="180px" prop="address" label="地址"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column v-if="$fieldShowFunc('zh_dh')" min-width="130px" prop="tel" label="电话" show-overflow-tooltip>
          </el-table-column>
        </el-table>
      </div>
      <div class="page-footer">
        <el-pagination class="el-pagination" @current-change="handleCurrentChange" :current-page="page" :page-size="num"
          @size-change="handleSizeChange" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </div>
    <!-- 新增账户 -->
    <el-dialog :modal-append-to-body="false" :before-close="cancelCompanyFunc" destroy-on-close
      :title="`${formInlineCompany.company_id ? '修改' : '新增'}${formInlineCompany.account_type == 1 ? '主体' : '往来'}账户`"
      :visible.sync="dialogVisibleCompany" width="490px">
      <el-form ref="ruleFormCompany" :rules="rulesCompany" :model="formInlineCompany" label-width="100px"
        label-position="left">
        <el-form-item label="账户类型" prop="type" v-if="formInlineCompany.account_type == 1">
          <el-radio-group v-model="formInlineCompany.type">
            <el-radio :label="1">公户</el-radio>
            <el-radio :label="2">私户</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="账户类型" prop="type" v-else>
          <el-radio-group v-model="formInlineCompany.type" @change="userTypeChange">
            <el-radio :label="1">客户</el-radio>
            <el-radio :label="2">工程经理</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="客户" prop="admin_id"
          v-if="formInlineCompany.type == 1 && formInlineCompany.account_type == 2">
          <el-select filterable class="form-width2" v-model="formInlineCompany.admin_id" placeholder="请选择">
            <el-option v-for="item in userListOption" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工程经理" prop="admin_id"
          v-if="formInlineCompany.type == 2 && formInlineCompany.account_type == 2">
          <el-select filterable class="form-width2" v-model="formInlineCompany.admin_id" placeholder="请选择">
            <el-option v-for="item in gcUserList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="账户名称" prop="account_name">
          <el-input clearable class="form-width2" v-model="formInlineCompany.account_name"
            placeholder="输入账户名称"></el-input>
        </el-form-item>
        <el-form-item label="账号" prop="account_number">
          <el-input clearable class="form-width2" v-model="formInlineCompany.account_number"
            placeholder="输入账号"></el-input>
        </el-form-item>
        <el-form-item label="开户行" prop="opening_bank">
          <el-input clearable class="form-width2" v-model="formInlineCompany.opening_bank"
            placeholder="输入账开户行"></el-input>
        </el-form-item>
        <!--  prop="Tax_ID" -->
        <el-form-item label="税号">
          <el-input clearable class="form-width2" v-model="formInlineCompany.Tax_ID" placeholder="输入税号"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input clearable class="form-width2" v-model="formInlineCompany.address" placeholder="输入地址"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="tel">
          <el-input maxlength="11" clearable class="form-width2" v-model="formInlineCompany.tel"
            placeholder="输入电话"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button :loading="addLoading" type="primary" @click="submitCompanyFunc">提交</el-button>
        <el-button :loading="addLoading" @click="cancelCompanyFunc">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import adminApi from "@/api/adminApi";
import commonApi from "@/api/common";
import { getUserInfo } from "@/utils/auth";
import companyApi from "@/api/companyApi";
export default {
  name: "accountManagement",
  components: {},
  data() {
    var validateTel = (rule, value, callback) => {
      const reg = /^((\+|00)86)?1((3[\d])|(4[5,6,7,9])|(5[0-3,5-9])|(6[5-7])|(7[0-8])|(8[\d])|(9[1,8,9]))\d{8}$/;
      if (!reg.test(value)) {
        callback(new Error('请输入电话'));
      } else {
        callback();
      }
    };
    var validateAdmin_id = (rule, value, callback) => {
      if (!value) {
        callback(new Error(this.formInlineCompany.type == 1 ? '请选择客户' : '请选择工程经理'));
      } else {
        callback();
      }
    };
    return {
      activeName: "1",
      tableLoading: false,
      userInfo: "",
      tableData: [],
      formSearch: {
        type: "",
        account_name: "",
        account_number: "",
        opening_bank: "",
        Tax_ID: "",
        address: "",
        tel: "",
      },
      moreSearchShow: false,
      page: 1,
      num: 10,
      total: 0,
      addLoading: false,
      pageLoading: false,
      formInlineCompany: {
        type: 1,
        account_name: "",
        account_number: "",
        opening_bank: "",
        Tax_ID: "",
        address: "",
        tel: "",
        account_type: "",
        admin_id: ""
      },
      rulesCompany: {
        account_name: [
          { required: true, message: '请输入账户名称', trigger: 'change' },
        ],
        account_number: [
          { required: true, message: '请输入账号', trigger: 'change' },
        ],
        opening_bank: [
          { required: true, message: '请输入开户行', trigger: 'change' },
        ],
        Tax_ID: [
          { required: true, message: '请输入税号', trigger: 'change' },
        ],
        address: [
          { required: true, message: '请输入地址', trigger: 'change' },
        ],
        tel: [
          { required: true, validator: validateTel, trigger: 'change' },
        ],
        admin_id: [
          { required: true, validator: validateAdmin_id, trigger: 'change' },]
      },
      dialogVisibleCompany: false,
      multipleSelection: [],
      userListOption: [],//客户列表
      gcUserList: [],//工程经理列表
      permission: [],//操作权限
    };
  },
  watch: {},
  computed: {},
  activated() {
    // 监听窗口大小变化事件
    window.addEventListener('resize', this.handleResize);
    this.onSearch();
  },
  destroyed() {
    window.removeEventListener('resize', this.handleResize);
    // 移除窗口大小变化事件监听器，防止内存泄漏
    if (this.resizeObserver) {
      // 停止观察目标元素，防止内存泄漏
      this.resizeObserver.disconnect();
    }
  },
  deactivated() {
    window.removeEventListener('resize', this.handleResize);
    // 移除窗口大小变化事件监听器，防止内存泄漏
    if (this.resizeObserver) {
      // 停止观察目标元素，防止内存泄漏
      this.resizeObserver.disconnect();
    }
  },
  mounted() {
    this.handleResize();
    // 监听窗口大小变化事件
    window.addEventListener('resize', this.handleResize);
    // 操作权限
    this.$getHtmlAuthority(this.$route.path).then(res => {
      console.log(res, "getHtmlAuthority");
      this.permission = res.data.permission;
    })
    this.userInfo = getUserInfo();
    this.getCompanyList();//账户列表
    this.getUserList();//客户列表列表
    this.getAdminList();//工程经理列表
  },
  methods: {
    handleResize() {
      const target = this.$refs.targetElement;
      const searchBox = this.$refs.searchBox;
      const pageList = this.$refs.pageList;
      // 创建 ResizeObserver 实例
      const resizeObserver = new ResizeObserver(entries => {
        setTimeout(() => {
          console.log('元素变为:', searchBox.offsetHeight);
          // searchBox.offsetHeight + 'px'
          pageList.style.height = 'calc(100% - ' + (searchBox.offsetHeight + 15) + 'px)';
        }, 0);
      });
      // 开始观察目标元素
      resizeObserver.observe(target);

      // 存储 resizeObserver 实例，以便在组件销毁时停止观察
      this.resizeObserver = resizeObserver;
    },
    // -----------------------------删除--------------------------------------
    delFunc() {
      let multipleSelection = this.multipleSelection;
      let company_idArr = [];
      multipleSelection.forEach(item => {
        company_idArr.push(item.id);
      })
      this.$confirm('此操作将永久删除已勾选账户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.delCompany(company_idArr);
      }).catch(() => {
      });
    },
    delCompany(id_arr) {
      companyApi.delCompany({ id_arr }).then(res => {
        console.log(res, "删除账户")
        if (res.code == 200) {
          this.onSearch();
        }
        this.$message({
          type: res.code == 200 ? 'success' : 'warning',
          message: res.message
        })
      })
    },
    // -----------------------------编辑--------------------------------------
    editFunc() {
      let multipleSelection = this.multipleSelection;
      this.getCompanyDetail(multipleSelection[0].id);
    },
    getCompanyDetail(company_id) {
      companyApi.getCompanyDetail({ company_id }).then(res => {
        console.log(res, "账户详情")
        if (res.code == 200) {
          this.dialogVisibleCompany = true;
          this.formInlineCompany = {
            company_id: res.data.id,
            type: res.data.type,
            account_name: res.data.account_name,
            account_number: res.data.account_number,
            opening_bank: res.data.opening_bank,
            Tax_ID: res.data.Tax_ID,
            address: res.data.address,
            tel: res.data.tel,
            account_type: res.data.account_type,
            admin_id: res.data.admin_id
          }
        }
      })
    },
    // -----------------------------列表多选--------------------------------------
    handleSelectionChange(e) {
      console.log(e);
      this.multipleSelection = e;
    },
    // -----------------------------账户列表--------------------------------------
    getCompanyList() {
      let formSearch = this.formSearch;
      this.tableLoading = true;
      companyApi.getCompanyList({
        page: this.page,
        num: this.num,
        account_type: this.activeName,
        type: formSearch.type,
        account_name: formSearch.account_name,
        type: formSearch.type || '',
        account_number: formSearch.account_number,
        opening_bank: formSearch.opening_bank,
        Tax_ID: formSearch.Tax_ID,
        address: formSearch.address,
        tel: formSearch.tel,
      }).then(res => {
        console.log(res, "账户列表")
        this.tableLoading = false;
        if (res.code == 200) {
          this.tableData = res.data.list;
          this.total = res.data.max;
        }
      })
    },
    // -----------------------------添加/更新账户--------------------------------------
    addCompanyFunc(account_type) {
      this.formInlineCompany.account_type = account_type;
      this.dialogVisibleCompany = true;
    },
    submitCompanyFunc() {
      let formInlineCompany = this.formInlineCompany;
      console.log(formInlineCompany, "formInlineCompany")
      this.$refs.ruleFormCompany.validate((valid) => {
        if (valid) {
          if (formInlineCompany.company_id) {
            this.updCompany({
              company_id: formInlineCompany.company_id,
              type: formInlineCompany.type,
              account_name: formInlineCompany.account_name,
              account_number: formInlineCompany.account_number,
              opening_bank: formInlineCompany.opening_bank,
              Tax_ID: formInlineCompany.Tax_ID,
              address: formInlineCompany.address,
              tel: formInlineCompany.tel,
              account_type: formInlineCompany.account_type,
              admin_id: formInlineCompany.admin_id
            })
            return;
          }
          this.addCompany({
            type: formInlineCompany.type,
            account_name: formInlineCompany.account_name,
            account_number: formInlineCompany.account_number,
            opening_bank: formInlineCompany.opening_bank,
            Tax_ID: formInlineCompany.Tax_ID,
            address: formInlineCompany.address,
            tel: formInlineCompany.tel,
            account_type: formInlineCompany.account_type,
            admin_id: formInlineCompany.admin_id
          })
        }
      })
    },
    cancelCompanyFunc() {
      this.formInlineCompany = {
        type: 1,
        account_name: "",
        account_number: "",
        opening_bank: "",
        Tax_ID: "",
        address: "",
        tel: "",
        account_type: "",
        admin_id: ""
      }
      this.dialogVisibleCompany = false;
    },
    addCompany(obj) {
      this.addLoading = true;
      companyApi.addCompany(obj).then(res => {
        console.log(res, "添加账户")
        this.addLoading = false;
        if (res.code == 200) {
          this.onSearch(1);
          this.cancelCompanyFunc();
        }
        this.$message({
          type: res.code == 200 ? 'success' : 'warning',
          message: res.message
        })
      })
    },
    updCompany(obj) {
      this.addLoading = true;
      companyApi.updCompany(obj).then(res => {
        console.log(res, "更新账户")
        this.addLoading = false;
        if (res.code == 200) {
          this.onSearch();
          this.cancelCompanyFunc();
        }
        this.$message({
          type: res.code == 200 ? 'success' : 'warning',
          message: res.message
        })
      })
    },
    // -----------------------------客户列表--------------------------------------
    getUserList() {
      adminApi.getUserList({
        page: 1,
        num: 999
      }).then(res => {
        console.log(res, "客户列表")
        if (res.code == 200) {
          this.userListOption = res.data.list;
        }
      })
    },
    // -----------------------------客户/工程经理切换--------------------------------------
    userTypeChange(e) {
      console.log(e)
      this.formInlineCompany.admin_id = "";
    },
    // -----------------------------工程经理列表--------------------------------------
    getAdminList() {
      adminApi.getAdminList({
        page: 1,
        num: 999,
        identity: 2,
        position_id: [7]
      }).then(res => {
        console.log(res, "工程经理列表")
        if (res.code == 200) {
          this.gcUserList = res.data.list;
        }
      })
    },
    // ----------------------------table点击行-选中----------------------------
    handleHighlightChangeTable(row) {
      if (!row.disabled) {
        this.$refs.table.toggleRowSelection(row);
      }
    },
    // -----------------------------------------------------------------------------------
    // 单页数据量修改
    handleSizeChange(e) {
      this.num = e;
      this.page = 1;
      this.getCompanyList();
    },
    // 页面权限
    getHtmlAuthority() {
      commonApi
        .getHtmlAuthority({
          path: this.$route.path,
        })
        .then((res) => {
          console.log(res, "页面权限");
          if (res.code == 200) {
            this.HtmlAuthority = res.data;
          }
        });
    },
    // 搜索
    onSearch(page) {
      page = typeof page == 'number' ? page : this.page;
      this.page = page;
      this.getCompanyList();
    },
    // 翻页
    handleCurrentChange(page) {
      this.page = page;
      this.getCompanyList();
    },
    moreSearchFunc() {
      this.moreSearchShow = !this.moreSearchShow;
      this.$nextTick(() => {
        this.handleResize();
      })
    },
    // tab点击
    tabClickFunc(e) {
      this.handleResize();
      this.getCompanyList();
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./index.scss";
@import '@/styles/listPage.scss';
</style>